<!--
 * @Author: 王俊杰 “251082517@qq.com”
 * @Date: 2024-05-11 11:26:43
 * @LastEditors: 王俊杰 “251082517@qq.com”
 * @LastEditTime: 2024-05-13 09:52:30
 * @FilePath: /vite-project/src/views/components/advertise/index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!-- 页面漂浮的广告效果 -->
<template>
  <div
    class="advertise"
    id="advertise"
    @mousemove="onMousemove"
    @mouseout="onMouseout"
  ></div>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const times = ref(null)

// 初始化
const initPopup = () => {
  let count = 20
  let stepX = 1
  let stepY = 1
  let pop = document.querySelector('#advertise')
  let popWidth = pop.offsetWidth
  let popHeight = pop.offsetHeight
  let clientW = document.body.clientWidth
  let clientH = document.body.clientHeight
  // debugger
  let x = parseInt(pop.getBoundingClientRect().left)
  let y = parseInt(pop.getBoundingClientRect().top)
  times.value = setInterval(() => {
    let distenceX = clientW - x
    let distenceY = clientH - y
    if (distenceX - popWidth < 0 || distenceX > clientW) {
      stepX = -stepX
    }
    if (distenceY - popHeight < 0 || distenceY > clientH) {
      stepY = -stepY
    }
    x += stepX
    y += stepY
    changePos(pop, x, y)
  }, count)
}
// 设置位置
const changePos = (pop, x, y) => {
  pop.style.left = x + 'px'
  pop.style.top = y + 'px'
}
// 鼠标移入
const onMousemove = () => {
  if (times.value) {
    clearInterval(times.value)
  }
}
// 鼠标移除
const onMouseout = () => {
  if (times.value) {
    clearInterval(times.value)
  }
  initPopup()
}

onMounted(() => {
  initPopup()
})
</script>

<style lang="scss" scoped>
.advertise {
  width: 250px;
  height: 100px;
  background: #e3e3e3;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 999;
  cursor: pointer;
}
</style>
